package com.sky.task;


import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * 自定义定时任务，实现订单状态定时处理
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 支付超时订单
     */
    @Scheduled(cron = "0 * * * * ?") //每分钟查一次
    public void Overtime(){
        log.info("支付超时:{}",new Date());


        //1.按当前时间-15分钟判断订单是否超时
            //1.1获取15分钟前的时间
        LocalDateTime oldTime = LocalDateTime.now().plusMinutes(-15);
            //1.2查询过去15分钟,且状态为待支付的的订单列表
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT,oldTime);

        //2.修改订单状态为:取消订单
        if (ordersList != null && ordersList.size() > 0){
            ordersList.stream().forEach(orders -> {
                orders.setStatus(Orders.CANCELLED); //修改状态为已取消
                orders.setCancelReason("支付超时,自动取消");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            });
        }
    }

    /**
     * 派送中订单
     */
    @Scheduled(cron = "0 0 1 * * ?") //每天1点查一次
    public void Delivering(){
        //1.根据当前时间,获得1个小时前的时间
        LocalDateTime oldTime = LocalDateTime.now().plusMinutes(-60);

        //2.根据得到的时间与订单状态为派送中,拿到订单列表
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS,oldTime);

        //3.修改状态
        if (ordersList != null && ordersList.size() > 0){
            ordersList.stream().forEach(orders -> {
                orders.setStatus(Orders.COMPLETED);
                //传参
                orderMapper.update(orders);
            });
        }
        log.info("派送中:{}",new Date());
    }
}
